import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart' hide SnackPosition;

import '../../common/index.dart';
import 'index.dart';

class CommunityPage extends GetView<CommunityController> {
  const CommunityPage({super.key});

  // 主视图
  Widget _buildView() {
    return CustomScrollView(
      controller: controller.scroll_controller,
      slivers: [
        SliverToBoxAdapter(
          child: Column(
            children: [
              SizedBox(height: 60.h),
              SizedBox(
                width: double.infinity,
                height: 175.h,
                child: Stack(
                  children: [
                    // 背景图片
                    Positioned(
                      bottom: 18.h,
                      right: 16.w,
                      child: Container(
                        width: 145.w,
                        height: 145.h,
                        decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage(AssetsImages.plaza),
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                    ),
                    Row(
                      children: [
                        SizedBox(width: 24.w),
                        // 返回按钮添加水波纹和缩放动画
                        TweenAnimationBuilder<double>(
                          duration: const Duration(milliseconds: 300),
                          tween: Tween<double>(begin: 0.8, end: 1.0),
                          builder: (context, value, child) {
                            return Transform.scale(scale: value, child: child);
                          },
                          child: InkWell(
                            onTap: () {
                              // 添加点击缩放效果
                              HapticFeedback.selectionClick();
                              RouteUtil.go(RouteNames.main);
                            },
                            borderRadius: BorderRadius.circular(10.r),
                            splashColor: Colors.white24,
                            child: Container(
                              height: 40.h,
                              width: 40.w,
                              padding: EdgeInsets.all(10.r),
                              decoration: BoxDecoration(
                                color: Color(0xFFCDFF5F),
                                borderRadius: BorderRadius.circular(10.r),
                              ),
                              child: SvgPicture.asset(
                                AssetsImages.back,
                                width: 20.w,
                                height: 20.h,
                              ),
                            ),
                          ),
                        ),
                        Spacer(),
                        // 添加按钮添加旋转动画
                        TweenAnimationBuilder<double>(
                          duration: const Duration(milliseconds: 500),
                          tween: Tween<double>(begin: 0, end: 1),
                          builder: (context, value, child) {
                            return Transform.rotate(
                              angle: value * 0.2,
                              child: Opacity(opacity: value, child: child),
                            );
                          },
                          child: InkWell(
                            onTap: () => {
                              HapticFeedback.mediumImpact(),
                              if (UserService().get_now_user() == null)
                                {
                                  SmartDialogHelper.show_snackbar(
                                    title: 'Notice',
                                    message:
                                        'Please login first before publishing',
                                    backgroundColor: Colors.black54,
                                    colorText: Colors.white,
                                  ),
                                }
                              else
                                {RouteUtil.push(RouteNames.release)},
                            },
                            splashColor: Colors.white24,
                            borderRadius: BorderRadius.circular(10.r),
                            child: Container(
                              height: 40.h,
                              width: 40.w,
                              padding: EdgeInsets.all(10.r),
                              decoration: BoxDecoration(
                                color: Color(0xFFCDFF5F),
                                borderRadius: BorderRadius.circular(10.r),
                              ),
                              child: SvgPicture.asset(
                                AssetsImages.add,
                                width: 20.w,
                                height: 20.h,
                              ),
                            ),
                          ),
                        ),
                        SizedBox(width: 24.w),
                      ],
                    ),
                    // 标题文字
                    Positioned(
                      top: 40.h,
                      left: 24.w,
                      child: TweenAnimationBuilder<double>(
                        duration: const Duration(milliseconds: 500),
                        tween: Tween<double>(begin: 0.9, end: 1),
                        builder: (context, value, child) {
                          return Transform.scale(
                            scale: value,
                            child: Opacity(opacity: value, child: child),
                          );
                        },
                        child: Text(
                          "Plant",
                          style: TextStyle(
                            fontSize: 48.sp,
                            fontWeight: FontWeight.w900,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
                    Positioned(
                      top: 100.h,
                      left: 24.w,
                      child: TweenAnimationBuilder<double>(
                        duration: const Duration(milliseconds: 700),
                        tween: Tween<double>(begin: 0.9, end: 1),
                        builder: (context, value, child) {
                          return Transform.scale(
                            scale: value,
                            child: Opacity(opacity: value, child: child),
                          );
                        },
                        child: Text(
                          "Plaza",
                          style: TextStyle(
                            fontSize: 48.sp,
                            fontWeight: FontWeight.w900,
                            color: Color(0xFFCDFF5F),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 10.h),
            ],
          ),
        ),

        // 帖子列表区域
        Obx(() {
          if (controller.is_loading.value) {
            return SliverFillRemaining(
              child: const Center(child: CircularProgressIndicator()),
            );
          }

          return SliverPadding(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            sliver: SliverGrid(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2, // 每行两个
                childAspectRatio: 0.8, // 宽高比
                crossAxisSpacing: 9.w, // 水平间距
                mainAxisSpacing: 12.h, // 垂直间距
              ),
              delegate: SliverChildBuilderDelegate((context, index) {
                final post = controller.posts[index];
                final user = controller.post_users[post.user_id];
                final firstImage = post.post_image_list.split(',').first;

                // 添加列表项的交错动画效果
                return AnimatedOpacity(
                  duration: Duration(milliseconds: 500),
                  opacity: 1.0,
                  curve: Curves.easeInOut,
                  child: AnimatedPadding(
                    duration: Duration(milliseconds: 300),
                    padding: EdgeInsets.only(top: 0),
                    child: _buildPostItem(post, user, firstImage, index),
                  ),
                );
              }, childCount: controller.posts.length),
            ),
          );
        }),
      ],
    );
  }

  // 单个帖子项
  Widget _buildPostItem(
    PostModel post,
    UserModel? user,
    String imageFile,
    int index,
  ) {
    final imagePathHandler = ImagePath();

    // 使用索引生成交错的动画延迟
    final delay = (index % 5) * 100;

    return AnimatedBuilder(
      animation: controller.animation_controller,
      builder: (context, child) {
        // 计算该项的进入动画进度
        final itemAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
          CurvedAnimation(
            parent: controller.animation_controller,
            curve: Interval(
              0.1 + (delay / 1000), // 根据索引延迟动画开始时间
              0.6 + (delay / 1000),
              curve: Curves.easeOutQuint,
            ),
          ),
        );

        return Transform.translate(
          offset: Offset(0, 20 * (1 - itemAnimation.value)),
          child: Opacity(opacity: itemAnimation.value, child: child),
        );
      },
      child: GestureDetector(
        onTap: () {
          HapticFeedback.lightImpact();
          RouteUtil.push(RouteNames.postDetail, extra: post);
        },
        behavior: HitTestBehavior.opaque,
        child: Hero(
          tag: 'post_${post.post_id}',
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(16.r),
              color: Colors.black26,
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.2),
                  blurRadius: 4,
                  offset: Offset(0, 2),
                ),
              ],
            ),
            clipBehavior: Clip.antiAlias,
            child: Stack(
              children: [
                // 帖子图片
                Positioned.fill(
                  child: FutureBuilder<List<String>>(
                    future: ImagePath.process_post_image_list(
                      post.post_image_list,
                    ),
                    builder: (context, snapshot) {
                      if (!snapshot.hasData || snapshot.data!.isEmpty) {
                        return Image.asset(
                          'assets/images/default_post.png',
                          fit: BoxFit.cover,
                        );
                      }

                      final firstImagePath = snapshot.data!.first;
                      return Image(
                        image: imagePathHandler.get_post_image(firstImagePath),
                        fit: BoxFit.cover,
                      );
                    },
                  ),
                ),

                // 底部信息栏
                Positioned(
                  bottom: 10.h,
                  left: 5,
                  right: 10,
                  child: TweenAnimationBuilder<double>(
                    duration: Duration(milliseconds: 400),
                    tween: Tween<double>(begin: 0, end: 1),
                    builder: (context, value, child) {
                      return Opacity(
                        opacity: value,
                        child: Transform.translate(
                          offset: Offset(0, (1 - value) * 10),
                          child: child,
                        ),
                      );
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 12.w,
                        vertical: 8.h,
                      ),
                      child: LayoutBuilder(
                        builder: (context, constraints) {
                          return Row(
                            children: [
                              SizedBox(width: 2.w),
                              // 用户头像
                              if (user != null)
                                CircleAvatar(
                                  backgroundImage: ImagePath().get_avatar_image(
                                    user.avatar_image,
                                  ),
                                  radius: 20.r,
                                ),

                              SizedBox(width: 2.w),

                              // 用户名
                              if (user != null)
                                Flexible(
                                  child: Container(
                                    constraints: BoxConstraints(maxWidth: 80.w),
                                    child: Text(
                                      user.name ?? 'Unknown',
                                      style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 12.sp,
                                        fontWeight: FontWeight.w900,
                                      ),
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ),
                                ),

                              Spacer(),

                              // 点赞按钮
                              GestureDetector(
                                onTap: () {
                                  HapticFeedback.lightImpact();
                                  controller.toggle_like(post.post_id);
                                  return;
                                },
                                behavior: HitTestBehavior.opaque,
                                child: Container(
                                  width: 40.w,
                                  height: 40.h,
                                  decoration: BoxDecoration(
                                    color: Colors.black.withOpacity(0.6),
                                    shape: BoxShape.circle,
                                    boxShadow: [
                                      BoxShadow(
                                        color: Colors.black.withOpacity(0.2),
                                        spreadRadius: 1,
                                        blurRadius: 3,
                                        offset: Offset(0, 2),
                                      ),
                                    ],
                                  ),
                                  child: AnimatedSwitcher(
                                    duration: Duration(milliseconds: 300),
                                    transitionBuilder: (child, animation) {
                                      return ScaleTransition(
                                        scale: animation,
                                        child: child,
                                      );
                                    },
                                    child: controller.is_liked(post.post_id)
                                        ? SvgPicture.asset(
                                            AssetsImages.goodAfter,
                                            key: ValueKey('liked'),
                                            width: 24.w,
                                            height: 24.h,
                                            color: Color(0xFFCDFF5F),
                                          )
                                        : SvgPicture.asset(
                                            AssetsImages.good,
                                            key: ValueKey('unliked'),
                                            width: 24.w,
                                            height: 24.h,
                                            color: Colors.white,
                                          ),
                                  ),
                                ),
                              ),
                              SizedBox(width: 2.w),
                            ],
                          );
                        },
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<CommunityController>(
      init: CommunityController(),
      id: "community",
      builder: (_) {
        return Scaffold(
          extendBody: true,
          body: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(AssetsImages.bg),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(top: false, bottom: false, child: _buildView()),
          ),
        );
      },
    );
  }
}
